<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 添加角色按钮 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="addRoleDialogVisible = true">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表 -->
      <el-table stripe border :data="roleList">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row :class="['bdbottom', i1 === 0 ? 'bdtop' : '']" v-for="(item1, i1) in scope.row.children" :key="item1.id" type="flex" align="middle">
              <el-col :span="5">
                <el-tag closable @close="removeRightsById(scope.row, item1.id)">{{item1.authName}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <el-col :span="19">
                <el-row v-for="(item2, i2) in item1.children" :key="item2.id" :class="[i2===0 ? '' : 'bdtop']" type="flex" align="middle">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeRightsById(scope.row, item2.id)">{{item2.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18">
                    <el-tag v-for="item3 in item2.children" :key="item3.id" type="warning" closable @close="removeRightsById(scope.row, item3.id)">{{item3.authName}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="editRole(scope.row.id)">编辑</el-button>
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRoleById(scope.row.id)">删除</el-button>
            <el-tooltip content="分配权限" placement="top" effect="dark" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightsDialog(scope.row)">分配权限</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色 Dialog -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRoleDialogVisible"
      width="50%" @close="addRoleDialogClosed">
      <el-form
        label-width="80px"
        :model="addRoleInfo"
        :rules="addRoleFormRules"
        ref="addRoleFormRef">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleInfo.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleInfo.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleDialog">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色 Dialog -->
    <el-dialog
      title="修改角色信息"
      :visible.sync="editRoleDialogVisible"
      width="50%"
      @close="editRoleDialogClose">
      <el-form
        label-width="80px"
        :model="editRoleForm"
        :rules="editRoleFormRules"
        ref="editRoleFormRef"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleDialog">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 Dialog -->
    <el-dialog title="分配权限" :visible.sync="setRightsDialogVisible" width="50%" @close="resetTree">
      <!-- 树形权限列表 -->
      <el-tree
        ref="treeRef"
        :data="rightsList"
        show-checkbox
        node-key="id"
        :default-checked-keys="defaultKeys"
        :props="treeProps"
        default-expand-all>
      </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="getTreeKeys">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      roleList: [],
      setRightsDialogVisible: false,
      rightsList: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      defaultKeys: [],
      roleId: '',
      // 添加角色弹出的对话框的显隐
      addRoleDialogVisible: false,
      addRoleInfo: {
        roleName: '',
        roleDesc: ''
      },
      addRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      },
      // 编辑角色弹出层的显隐
      editRoleDialogVisible: false,
      editRoleForm: {
        roleName: '',
        roleDesc: ''
      },
      editRoleFormRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      if(res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      this.roleList = res.data
      // console.log(res.data)
    },
    // 通过 权限id 移除对应权限
    removeRightsById(role, rightsid) {
      this.$msgbox.confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightsid}`)
        if(res.meta.status !== 200) return this.$message.error('取消权限失败')
        // console.log(res.data)
        role.children = res.data
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 点击 分配权限 按钮
    async showSetRightsDialog(role) {
      const { data: res } = await this.$http.get('rights/tree')
      if(res.meta.status !== 200) return this.$message.error('获取分配权限列表失败')
      this.rightsList = res.data
      this.roleId = role.id
      this.getThreeNode(role, this.defaultKeys)
      this.setRightsDialogVisible = true
    },
    // 通过递归函数获取角色下所有三级权限的id 并保存到defaultKeys中
    getThreeNode(node, arr) {
      if(!node.children) return arr.push(node.id)
      node.children.forEach(element => {
        this.getThreeNode(element, arr)
      })
    },
    // 点击 分配权限Dialog上 确定 按钮
    async getTreeKeys() {
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if(res.meta.status !== 200) return this.$message.error('更新角色权限失败')
      this.$message.success(res.meta.msg)
      this.setRightsDialogVisible = false
      this.getRolesList()
    },
    // 每次关闭 分配权限Dialog 都清空默认选择的节点
    resetTree() {
      this.defaultKeys = []
    },
    // 删除角色
    deleteRoleById(id) {
      this.$msgbox.confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$http.delete('roles/' + id)
        if(res.meta.status !== 200) return this.$message.error('删除角色失败')
        this.$message.success('删除角色成功')
        this.getRolesList()
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },
    // 添加角色对话框关闭 重置表单内容
    addRoleDialogClosed() {
      this.$refs.addRoleFormRef.resetFields()
    },
    // 点击 添加角色 对话框中的 确定 按钮添加角色
    addRoleDialog() {
      this.$refs.addRoleFormRef.validate(async valid => {
        if(!valid) return
        const { data: res } = await this.$http.post('roles', this.addRoleInfo)
        if(res.meta.status !== 201) return this.$message.error('添加角色失败')
        this.$message.success('添加角色成功')
        this.addRoleDialogVisible = false
        this.getRolesList()
      })
    },
    // 点击 编辑 按钮
    async editRole(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if(res.meta.status !== 200) return this.$message.error('获取角色信息失败')
      this.editRoleForm = res.data
      this.editRoleDialogVisible = true
    },
    // 监听 编辑角色 对话框的关闭事件
    editRoleDialogClose() {
      this.$refs.editRoleFormRef.resetFields()
    },
    // 点击 编辑角色 对话框的 确定按钮
    editRoleDialog() {
      this.$refs.editRoleFormRef.validate(async valid => {
        if(!valid) return
        const { data: res } = await this.$http.put('roles/' + this.editRoleForm.roleId, {
          roleName: this.editRoleForm.roleName,
          roleDesc: this.editRoleForm.roleDesc
        })
        if(res.meta.status !== 200) return this.$message.error('角色信息修改失败')
        this.$message.success('角色信息修改成功')
        this.editRoleDialogVisible = false
        this.getRolesList()
      })
    }
  }
}
</script>
<style lang="less" scoped>
.el-table {
  font-size: 12px;
  margin-top: 20px;
}
.el-tag{
  margin: 7px;
}
.bdtop{
  border-top: 1px solid #eeeeee;
}
.bdbottom{
  border-bottom: 1px solid #eeeeee;
}
</style>
